package wjx.database.view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

import wjx.database.bean.JTableUtils;
import wjx.database.bean.StringUtil;
import wjx.database.jdbc.JDBCUtils;

public class DeleteFrm extends JFrame {

	private int num;
	private int count = 0;

	private JPanel contentPane;
	private JLabel label1, label2, label3, label;
	private Box box, box1, box2, box3, box4, box5, box7, box8;
	private JButton button1, button2, button3, button4, button5;
	private JTable table1, table2;
	private JScrollPane scroll1, scroll2;
	private DefaultTableModel modelE;

	private String[] listName;
	private String[] qQuery;
	private String[] type;
	private static List<String> primaryK = new ArrayList<>();
	private String title;
	private String sql;
	private String tableName = "";
	private String[][] data = null;
	private String oldValue = "";
	private ResultSet rs;
	private String dlRow;
	private String dlAll;
	private String code = "";

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					EditFrm frame = new EditFrm("new_table");
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public DeleteFrm(String name) {
		code = JDBCUtils.GetTableRemarks(name);
		tableName = name;
		primaryK = JDBCUtils.GetPriKey(name);
		setTitle("删除-表'" + name + "'");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setResizable(false);
		setBounds(100, 100, 700, 600);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));

		// 获取表字段名和对应类型
		List<String> queryList = JDBCUtils.GetTableColAnd(name);
		String[] mid = new String[queryList.size()];
		queryList.toArray(mid);

		qQuery = new String[queryList.size() / 2];
		type = new String[queryList.size() / 2];
		queryList.toArray(mid);
		for (int i = 0; i < queryList.size() / 2; i++) {
			qQuery[i] = mid[2 * i];
			type[i] = mid[2 * i + 1];
		}

		listName = new String[qQuery.length];
		num = qQuery.length;
		for (int i = 0; i < num; i++) {
			if( code.equals(qQuery[i])) {
				listName[i] = qQuery[i] + '(' + type[i] + "[加密列])";
				continue ;
			}
			listName[i] = qQuery[i] + '(' + type[i] + ')';
		}

		// 显示查找条件table1
		label = new JLabel("查找想要删除的记录(支持<、>、=条件查询)");
		label.setFont(new Font("Lucida Grande", 1, 15));
		title = " select * from databaseManager." + name;
		label1 = new JLabel(title);
		label2 = new JLabel(" where ");

		table1 = new JTable(1, num);
		DefaultTableModel model = (DefaultTableModel) table1.getModel();
		model.setColumnIdentifiers(listName);
		table1.setModel(model);
		scroll1 = new JScrollPane(table1);
//		table1.setPreferredScrollableViewportSize(new Dimension(num * 100, 32));
		JTableUtils.setTable(table1);
		scroll1.setPreferredSize(new Dimension(700,65));

		// 加载数据
		try {
			rs = JDBCUtils.query(title);
			// 加载data
			rs.last();
			data = new String[rs.getRow()][qQuery.length];
			rs = JDBCUtils.query(title);
			int cnt = 0;
			while (rs.next()) {
				for (int j = 0; j < qQuery.length; j++) {
					data[cnt][j] = rs.getString(qQuery[j]);
					if(code.equals(qQuery[j])) {
						MainFrm.myt.getEn(data[cnt][j]);
						synchronized(MainFrm.myt){
							MainFrm.myt.wait();
						}
						data[cnt][j] += '(' + MainFrm.myt.res + ')';
					}
					System.out.println(data[cnt][j]);
				}
				cnt++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// table2显示表的全部数据
		table2 = new JTable();
		modelE = new DefaultTableModel(data, qQuery);
		table2.setModel(modelE);
//		table2.setPreferredScrollableViewportSize(new Dimension(num * 100, 120));
		JTableUtils.setTable(table2);
		scroll2 = new JScrollPane(table2);

		button1 = new JButton("查找");
		button1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				queryActionPerformed(e);
			}
		});

		button3 = new JButton("重置");
		button3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				clearActionPerformed(e);
			}
		});

		button2 = new JButton("退出");
		button2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				quitActionPerformed(e);
			}
		});

		button4 = new JButton("删除选中行");
		button4.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				deleteRow(e);
			}
		});

		button5 = new JButton("删除查询到的全部数据");
		button5.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				deleteALlRow(e);
			}
		});

		box8 = Box.createHorizontalBox();
		box8.add(button5);
		box8.add(button4);

		label3 = new JLabel("查询到符合您输入条件的结果如下");
		label3.setFont(new java.awt.Font("Lucida Grande", Font.PLAIN, 16));
		JLabel lb = new JLabel("(点击表格选择想要删除的数据行)");
		lb.setFont(new Font("Lucida Grande", 1, 13));
		// 箱式布局
		box1 = Box.createHorizontalBox();
		box1.add(label);
		box2 = Box.createHorizontalBox();
		box2.add(label1);
		box2.add(label2);

		box5 = Box.createHorizontalBox();
		box5.add(scroll1);

		box3 = Box.createHorizontalBox();
		box3.add(button1);
		box3.add(button3);
		box3.add(button2);

		box7 = Box.createHorizontalBox();
		box7.add(label3);
		Box bx1 = Box.createHorizontalBox();
		bx1.add(lb);

		box4 = Box.createHorizontalBox();
		box4.add(scroll2);

		box = Box.createVerticalBox();
		box.add(box1);
		box.add(Box.createVerticalStrut(5));
		box.add(box2);
		box.add(Box.createVerticalStrut(10));
		box.add(box5);
		box.add(box3);
		box.add(Box.createVerticalStrut(10));
		box.add(box7);
		box.add(bx1);
		box.add(Box.createVerticalStrut(5));
		box.add(box8);
		box.add(box4);

		contentPane.add(box);
		setContentPane(contentPane);
//		pack();
		this.setLocationRelativeTo(null);
	}

	protected void deleteALlRow(ActionEvent e) {
		// 删除条件查询得到的所有行
		int rs = -1;
		int result;
		if (StringUtil.isEmpty(dlAll)) {
			result = JOptionPane.showConfirmDialog(null, "这将清空表中的所有数据，是否确认进行该操作？", "确认删除", JOptionPane.YES_NO_OPTION);
			if (result == JOptionPane.YES_NO_OPTION) {

				try {
					rs = JDBCUtils.update("delete from databaseManager."+tableName);
				} catch (SQLException e1) {
					JOptionPane.showMessageDialog(null, "语法错误！请检查输入的查询条件！");
				}
				if (rs >= 0)
					JOptionPane.showMessageDialog(null, "清空表成功");
				modelE.setRowCount(0);
			}
			return;
		}
		String cond = "delete from databaseManager." + tableName + " where " + dlAll;

		System.out.println(cond);

		// 再次确认是否删除
		result = JOptionPane.showConfirmDialog(null, "确认删除查询到的所有数据？", "确认删除", JOptionPane.YES_NO_OPTION);

		if (result == JOptionPane.YES_NO_OPTION) {

			try {
				rs = JDBCUtils.update(cond);
			} catch (SQLException e1) {
				JOptionPane.showMessageDialog(null, "语法错误！请检查输入的查询条件！");
			}
			if (rs >= 0)
				JOptionPane.showMessageDialog(null, "删除成功");
			modelE.setRowCount(0);
		}

	}

	private void deleteRow(ActionEvent e) {
		// 删除表table2选择的行
		if (table2.getSelectedRows() == null) {
			JOptionPane.showMessageDialog(null, "您还未选择需要删除的数据行");
			return;
		}
		// 构建删除语句
		dlRow = "delete from databaseManager." + tableName + " where ";
		int len = primaryK.size();
		int lie, hang;
		hang = table2.getSelectedRow();
		String[] ns = new String[len];
		primaryK.toArray(ns);
		for (int i = 0; i < len; i++) {
			if (i > 0)
				dlRow += " AND ";
//			System.out.println(ns[i]);
			lie = modelE.findColumn(ns[i]);

			System.out.println("hang:" + hang + " lie:" + lie);
			if (type[lie].charAt(0) == 'V')
				dlRow += ns[i] + "='" + table2.getValueAt(hang, lie).toString() + "'";
			else
				dlRow += ns[i] + "=" + table2.getValueAt(hang, lie).toString();
		}
		System.out.println(dlRow);

		// 再次确认是否删除
		int result = JOptionPane.showConfirmDialog(null, "确认删除该行？", "确认删除", JOptionPane.YES_NO_OPTION);

		if (result == JOptionPane.YES_NO_OPTION) {
			// 执行删除语句
			try {
				int res = JDBCUtils.update(dlRow);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			// 提示删除成功
			JOptionPane.showMessageDialog(null, "删除成功！");
			int numrow = table2.getSelectedRows().length;
			for (int i = 0; i < numrow; i++) {
				modelE.removeRow(table2.getSelectedRow());
			}
		}

	}

	private void clearActionPerformed(ActionEvent e) {
		for (int i = 0; i < num; i++) {
			table1.setValueAt("", 0, i);
		}
	}

	private void quitActionPerformed(ActionEvent e) {
		// 退出
		int result = JOptionPane.showConfirmDialog(null, "是否退出删除操作？", "退出删除", JOptionPane.YES_NO_OPTION);
		// 退出窗口
		if (result == JOptionPane.YES_NO_OPTION)
			dispose();

	}

	private void queryActionPerformed(ActionEvent e) {
		dlAll = "";
		sql = title;
		String s;
		int cnt = 0;
		for (int i = 0; i < num; i++) {
			s = (String) table1.getValueAt(0, i);
			System.out.println("$value" + s);
			if (s == null || s.length() == 0)
				continue;
			if (cnt == 0)
				sql += " where ";
			if (cnt > 0) {
				sql += " AND ";
				dlAll += " AND ";
			}
			sql += qQuery[i] + s;
			dlAll += qQuery[i] + s;
			cnt++;
		}
		// 获取查询条件
		System.out.println("query :" + sql);
		System.out.println(dlAll);

		try {
			rs = JDBCUtils.query(sql);
			rs.last();
			data = new String[rs.getRow()][qQuery.length];
			rs = JDBCUtils.query(sql);
			int cnt_ = 0;
			while (rs.next()) {
				for (int j = 0; j < qQuery.length; j++) {
					data[cnt_][j] = rs.getString(qQuery[j]);
					if(code.equals(qQuery[j])) {
						MainFrm.myt.getEn(data[cnt_][j]);
						synchronized(MainFrm.myt){
							MainFrm.myt.wait();
						}
						data[cnt_][j] += '(' + MainFrm.myt.res + ')';
					}
					System.out.println(data[cnt_][j]);
				}
				cnt_++;
			}
		} catch (Exception e1) {
			JOptionPane.showMessageDialog(null, "语法错误！请检查您的输入！");
		}
		// 显示查询结果
		table2 = new JTable();
		modelE = new DefaultTableModel(data, qQuery);
		table2.setModel(modelE);
//		table2.setPreferredScrollableViewportSize(new Dimension(num * 100, 120));
		JTableUtils.setTable(table2);
		
		box.remove(box4);
		scroll2 = new JScrollPane(table2);

		box4.removeAll();
		box4.add(scroll2);

		box.add(box4);
		contentPane.add(box);
		remove(contentPane);

		setContentPane(contentPane);
//		pack();

		// 不可编辑

	}

}
